const {readJson,writeJson} = require('../../until/fs');
const {USER_JSON} = require('../../config/config.data');

// 用户信息
let userSearch = (req,res)=>{
    const {user} = req.body;
    // 读取用户数据
    let userData  = readJson(USER_JSON);

    let searchRes = userData.find(item=>item.user === user)

    if(!searchRes){
        res.send({code:0,msg:'用户信息读取失败',data:[]})
        return 
    }

    delete searchRes.pwd
    
    res.send({code:1,msg:'用户信息读取成功',data:searchRes})
}

let userEdit = (req,res) =>{
    const {submitData} = req.body

    let userData = readJson(USER_JSON);

    // 查找是否含有当前用户数据，锁定位置
    let index = userData.findIndex(item=>item.user === submitData.user)

    if(index === -1){
        res.send({code:0,msg:'编辑失败',data:{}})
        return 
    }
    // 增加密码
    submitData.pwd  = userData[index].pwd;
    submitData.loginTime  = userData[index].loginTime;
    
    // 替换原有数据
    
    userData[index] = {...submitData}
    
    // 写入json
    writeJson(USER_JSON,userData)

    res.send({code:0,msg:'编辑成功',data:userData})
}
module.exports = {
    userSearch,userEdit
}